<?php

class IndexController extends Zend_Controller_Action {
    private $_params;
    private $_sig;
    private $_facebook;

    public function init() {
        $params = $this -> getRequest() -> getParams();
        $this -> view -> controller = $params['controller'];
        $this -> view -> module = $params['module'];
        $this -> _sig = $params['signed_request'];

        $this -> _facebook = new Facebook_Facebook( array('appId' => '392331817510533', 'secret' => 'e7af4fd21e08419357dbea756e670c9f', 'session' => true, ));

        $this -> _params = $params;
    }

    public function indexAction() {
        try {
                $data = $this -> parse_signed_request($this -> _sig, 'e7af4fd21e08419357dbea756e670c9f');
                // var_dump($data);
                // die();
                if (empty($data["page"]["liked"])) {
                    echo "You are not a fan!";
                } else {
                    $user = $this->_facebook->getUser();
                    // var_dump($user);
                    // die();
                    if ($user) {
                        $permissions = $this -> _facebook -> api("/me/permissions", array('access_token' => $data['oauth_token']));
                        // var_dump($permissions);
                        // die();
                        if (array_key_exists('publish_stream', $permissions['data'][0])) {
                            // Permission is granted!
                            // Do the related task
                            $post_id = $this -> _facebook -> api('/' . $data['user_id'] . '/feed', 'post', array('message' => 'Yeah! Something is happening.'));
                            var_dump($post_id);
                            die();
                        } else {
                            // We don't have the permission
                            // Alert the user or ask for the permission!
                            $loginUrl = $this->_facebook->getLoginUrl(array("scope" => "publish_stream", 'redirect_uri' => 'http://www.facebook.com/UnionFunnyTeam/app_392331817510533'));
                            echo("<script> top.location.href='" . $loginUrl . "'</script>");
                            return;
                        }
                    } else {
                        // You have not logged in yet
                        $loginUrl = $this->_facebook->getLoginUrl(array('redirect_uri' => 'http://www.facebook.com/UnionFunnyTeam/app_392331817510533'));
                        // die($loginUrl);
                        // $this->_redirect($loginUrl);
                        echo("<script> top.location.href='" . $loginUrl . "'</script>");
                        return;
                    }
                }
        } catch(Facebook_FacebookApiException $exc) {
            var_dump($exc -> getMessage());
            die();
        }
    }

    function parse_signed_request($signed_request, $secret) {
        list($encoded_sig, $payload) = explode('.', $signed_request, 2);

        // decode the data
        $sig = $this -> base64_url_decode($encoded_sig);
        $data = json_decode($this -> base64_url_decode($payload), true);

        if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
            error_log('Unknown algorithm. Expected HMAC-SHA256');
            return null;
        }

        // check sig
        $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
        if ($sig !== $expected_sig) {
            error_log('Bad Signed JSON signature!');
            return null;
        }

        return $data;
    }

    function base64_url_decode($input) {
        return base64_decode(strtr($input, '-_', '+/'));
    }

    public $link = array(1 => 'http://img2.news.zing.vn/2012/10/11/hot1.jpg', 2 => 'http://img.union.zing.vn/armory/sgn/wallfeedImages/friendWallfeed/2012-12-13/1355413621_154480_456878197693189_416644475_n.jpg', );

    public function helloAction() {
        if ($this -> _params['halt'] == 1) {
            die();
        }

        $this -> _helper -> layout -> disableLayout();
        $this -> _helper -> viewRenderer -> setNoRender();
        if ($this -> _params['index'] == 1) {
            //echo $this->link[$this->_params['index']];
            $this -> _redirect($this -> link[$this -> _params['index']]);
            return;
        }

        $image = file_get_contents($this -> link[$this -> _params['index']]);

        $this -> getResponse() -> clearBody();
        $this -> getResponse() -> setHeader('Content-Type', 'image/jpg');
        $this -> getResponse() -> setBody($image);
    }

    public function mainAction() {
    }

}
